package org.mii.safeguard_v1.util;

import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Iterator;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.PropertyUtils;

public class JsonBuilderUtil {

	final static JsonBuilderUtil instance = new JsonBuilderUtil();

	public static JsonBuilderUtil getInstance() {
		return instance;
	}

	// 私有构造函数，不让直接new
	private JsonBuilderUtil() {

	}

	/**
	 * 构建json格式的数据，传递一个json格式的集合类型，同时传递json要构建时候的id和value属性名称，返回json格式的数据
	 * 
	 * @param oriData：Collection
	 * @param properties：json中属性值在泛型T中的名称
	 * @return json格式数据example:<Br>
	 *         {{id:10,value:qqqq},{id:11,value:xxx},{id:12:value:www}}
	 * @author QUANXIWEI
	 */
	public <T> String buildJsonData(Collection<T> oriData, String... properties) {
		if (oriData == null || oriData.size() == 0)
			return "";
		if (properties == null || properties.length == 0)
			return "";

		JSONArray array = new JSONArray();
		JSONObject jsonObject;

		Iterator<T> iterator = oriData.iterator();
		try {
			while (iterator.hasNext()) {
				T element = iterator.next();
				jsonObject = new JSONObject();
				for (int i = 0; i < properties.length; i++) {
					jsonObject.put(properties[i], PropertyUtils.getProperty(
							element, properties[i]));
				}
				array.add(jsonObject);
			}

		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return array.toString();
	}
}
